package cn.gailvlun.gll.presentation.xroom.adapter

import android.app.Activity
import android.content.Context
import android.graphics.Typeface
import android.support.v4.app.ActivityOptionsCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Spannable
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import cn.gailvlun.gll.R
import cn.gailvlun.gll.chatlib.bean.CrossMessage
import cn.gailvlun.gll.chatlib.bean.CrossMessageType
import cn.gailvlun.gll.chatlib.message.Message
import cn.gailvlun.gll.chatlib.message.MessageType
import cn.gailvlun.gll.presentation.base.App
import cn.gailvlun.gll.presentation.chat.PhotoActivity
import cn.gailvlun.gll.presentation.xroom.length
import cn.gailvlun.gll.util.DateUtil
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.github.markzhai.recyclerview.BaseViewAdapter
import com.github.markzhai.recyclerview.MultiTypeAdapter
import com.makeramen.roundedimageview.RoundedImageView
import io.realm.OrderedRealmCollection
import io.realm.RealmRecyclerViewAdapter
import kotlin.math.round





class CrossRoomChatAdapter : MultiTypeAdapter {
    val messageType = ArrayList<Int>()

    var mContext: Context

    constructor(context: Context) : super(context) {
        mContext = context

        var viewType = 0
        for ((index, value) in CrossMessageType.values().withIndex()) {
            when {
                index < 5 -> addViewTypeToLayoutMap(viewType++, R.layout.item_cross_room_chat_system)
                index == 5 -> addViewTypeToLayoutMap(viewType++, R.layout.item_cross_room_time)
                else -> {
                    addViewTypeToLayoutMap(viewType++, R.layout.item_cross_room_chat_left)
                    addViewTypeToLayoutMap(viewType++, R.layout.item_cross_room_chat_right)
                }
            }
        }

        presenter = Presenter()
    }

    fun addLatest(viewModel: CrossMessage?, isScroll2Bottom: Boolean = true) {
        if (viewModel == null) {
            return
        }
        if (mCollection.size == 0 || !DateUtil.isInFiveMinute((mCollection[0] as CrossMessage).created,
                        viewModel.created)) {
            
            val timeMsg = CrossMessage()
            timeMsg.type = CrossMessageType.TIME
            timeMsg.created = viewModel.created

            val viewType = getViewType(timeMsg)
            this.messageType.add(0, viewType)
            super.add(0, timeMsg, viewType)
        }

        val viewType = getViewType(viewModel)
        messageType.add(0, viewType)
        super.add(0, viewModel, viewType)
        if (isScroll2Bottom) {

            scrollToBottom()
        }
    }

    private fun getViewType(item: CrossMessage): Int {
        return CrossMessageType.values().indexOf(item.type)
                .run {
                    if (this < 6) {
                        return@run this
                    }
                    if (!item.isMe) {
                        6 + (this - 6) * 2
                    } else {
                        6 + (this - 6) * 2 + 1
                    }
                }
    }

    var mLayoutManager: LinearLayoutManager? = null

    fun scrollToBottom() {
        
        if (mLayoutManager != null) {
            mLayoutManager?.scrollToPositionWithOffset(0, 0)
        }
    }

    inner class Presenter : BaseViewAdapter.Presenter {
        fun onClickPhoto(view: View, item: CrossMessage) {
            val options = ActivityOptionsCompat
                    .makeSceneTransitionAnimation(mContext as Activity,
                            view, mContext.getString(R.string.shared_image))

            PhotoActivity.openActivity(mContext, item.realImage, options.toBundle())
        }
    }

    object Util {
        @JvmStatic
        fun getSystemText(item: CrossMessage): Spannable? {
            return when (item.type) {
                CrossMessageType.BEFORE_OPEN -> {
                    SpannableString.valueOf(SpannableStringBuilder().append(
                            "系统随机分配角色\n" +
                                    "神秘人：${item.crossRoomInfo.first.owner.name}\n" +
                                    "解密人：${item.crossRoomInfo.second.owner.name}\n" +
                                    "第${if (item.round == 0) "一" else "二"}轮由${item.crossRoomInfo.first.owner.name}开始，系统将自动帮你出题"
                    ))

                }
                CrossMessageType.ANSWER_START -> {
                    SpannableString.valueOf(
                            SpannableStringBuilder().append(
                                    "${item.currentAnswerMan.name}可以开始提问啦，限时${item.crossRoomInfo.riddleTime}s\n" +
                                            "猜对了的话，按照规则，${item.currentQuestionMan.name}需分享一张照片哦～")
                                    .apply {
                                        val firstLength = item.currentAnswerMan.name.length
                                        val secondLength = item.crossRoomInfo.riddleTime.length()
                                        val thirdLength = item.currentQuestionMan.name.length
                                        setSpan(ForegroundColorSpan(App.getInstance().resources.getColor(R.color.apricot)),
                                                0, firstLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                                        setSpan(ForegroundColorSpan(App.getInstance().resources.getColor(R.color.apricot)),
                                                firstLength + 10 + secondLength + 13, firstLength + 10 + secondLength + 13 + thirdLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                                    }
                    )

                }
                CrossMessageType.LAST_TEN_SECOND -> {
                    SpannableString.valueOf(SpannableStringBuilder().append(
                            "只剩最后${item.crossRoomInfo.riddleCountDownTime}s了，抓紧时间～"
                    ))
                }
                CrossMessageType.ANSWER_DONE -> {
                    val questionManName = item.currentQuestionMan.name
                    val answerManName = item.currentAnswerMan.name
                    SpannableString.valueOf(
                            SpannableStringBuilder()
                                    .append("时间到！${answerManName}正在输入最终答案，无法及时回复新消息，${questionManName}需等待${item.crossRoomInfo.riddleAnswerTime}秒左右哦～")
                                    .apply {
                                        val firstLength = answerManName.length
                                        val secondLength = questionManName.length
                                        setSpan(ForegroundColorSpan(App.getInstance().resources.getColor(R.color.apricot)), 4, 4 + firstLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                                        setSpan(ForegroundColorSpan(App.getInstance().resources.getColor(R.color.apricot)), 4 + firstLength + 19, 4 + firstLength + 19 + secondLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                                    }
                    )
                }
                CrossMessageType.ANSWER_RESULT -> {
                    getAnswerResult(item)
                }
                else -> null
            }
        }

        private fun getAnswerResult(item: CrossMessage): Spannable {
            if (item.currentQuestionInfo.isAnswerRight) {
                return SpanUtils().append("厉害了，")
                        .append(item.currentAnswerMan.name).setForegroundColor(App.getInstance().resources.getColor(R.color.apricot))
                        .append("猜对啦！正确答案：")
                        .appendLine("${getAnswer(item)}").setForegroundColor(App.getInstance().resources.getColor(R.color.apricot))
                        .append("\n接下来，要进入一个很有趣的惩罚环节（限时")
                        .append("${item.crossRoomInfo.punishTime.div(60)}").setForegroundColor(App.getInstance().resources.getColor(R.color.apricot))
                        .append("分钟）：\n\n请")
                        .append(item.currentWelfareMan.name).setForegroundColor(App.getInstance().resources.getColor(R.color.apricot))
                        .append("出一个脑海里浮现的数字，")
                        .append(item.currentExposeMan.name).setForegroundColor(App.getInstance().resources.getColor(R.color.apricot))
                        .append("需发出相册中对应数字的照片，并分享照片背后的故事（拍摄/保存的时间、地点、原因等）")
                        .create()
            } else {
                return SpanUtils().append("啊咧，")
                        .append(item.currentAnswerMan.name).setForegroundColor(App.getInstance().resources.getColor(R.color.apricot))
                        .append("猜错啦！正确答案：")
                        .appendLine("${getAnswer(item)}").setForegroundColor(App.getInstance().resources.getColor(R.color.apricot))
                        .append("\n接下来，要进入一个很有趣的惩罚环节（限时")
                        .append("${item.crossRoomInfo.punishTime.div(60)}").setForegroundColor(App.getInstance().resources.getColor(R.color.apricot))
                        .append("分钟）：\n\n请")
                        .append(item.currentWelfareMan.name).setForegroundColor(App.getInstance().resources.getColor(R.color.apricot))
                        .append("出一个脑海里浮现的数字，")
                        .append(item.currentExposeMan.name).setForegroundColor(App.getInstance().resources.getColor(R.color.apricot))
                        .append("需发出相册中对应数字的照片，并分享照片背后的故事（拍摄/保存的时间、地点、原因等）")
                        .create()
            }
        }

        private fun getRoundResult(item: CrossMessage): String {
            return if (item.currentQuestionInfo.isAnswerRight) {
                "厉害了，${item.currentAnswerMan.name}猜对"
            } else {
                "啊咧，${item.currentAnswerMan.name}猜错"
            }
        }

        @JvmStatic
        fun getText(item: CrossMessage): CharSequence? {
            return when (item.type) {
                CrossMessageType.QUESTION -> {
                    SpannableString.valueOf(
                            SpanUtils().appendLine("嗨，很高兴认识！٩(｡・ω・｡)\uFEFFو\n")
                                    .appendLine("${getTitleBy(item)}\n").setBold()
                                    .append("${getRefBy(item)}")
                                    .create()
                    )
                }
                CrossMessageType.TEXT -> {
                    item.text
                }
                else -> null
            }
        }

        @JvmStatic
        fun getTextVisi(item: CrossMessage): Int {
            return when (item.type) {
                CrossMessageType.TEXT, CrossMessageType.QUESTION -> View.VISIBLE
                else -> View.GONE
            }
        }

        @JvmStatic
        fun getImageVisi(item: CrossMessage): Int {
            return when (item.type) {
                CrossMessageType.IMAGE -> View.VISIBLE
                else -> View.GONE
            }
        }

        private fun getTitleBy(crossMessage: CrossMessage?): String? {
            return when (crossMessage?.round) {
                0 -> crossMessage.crossRoomInfo.first.question
                1 -> crossMessage.crossRoomInfo.second.question
                else -> null
            }
        }

        private fun getRefBy(crossMessage: CrossMessage?) : String? {
            return when (crossMessage?.round) {
                0 -> crossMessage.crossRoomInfo.first.question_ref
                1 -> crossMessage.crossRoomInfo.second.question_ref
                else -> null
            }
        }

        private fun getAnswerManName(crossMessage: CrossMessage?): String? {
            return when (crossMessage?.round) {
                0 -> crossMessage.crossRoomInfo.second.owner.name
                1 -> crossMessage.crossRoomInfo.first.owner.name
                else -> null
            }
        }

        private fun getAnswer(crossMessage: CrossMessage?): String? {
            return when (crossMessage?.round) {
                0 -> crossMessage.crossRoomInfo.first.answer
                1 -> crossMessage.crossRoomInfo.second.answer
                else -> null
            }
        }

        private fun getQuestionMan(crossMessage: CrossMessage?): String? {
            return when (crossMessage?.round) {
                0 -> crossMessage.crossRoomInfo.first.owner.name
                1 -> crossMessage.crossRoomInfo.second.owner.name
                else -> null
            }
        }
    }
}

